<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2018/11/8
 * Time: 下午6:26
 */

namespace Api\Controller;

use Api\Service\ArticleService;
use Api\Service\GoodsService;
use Api\Service\MoneyLogService;
use Api\Service\OrderService;
use Api\Service\ThirdService;
use Api\Service\UserService;
use Api\Service\WithdrawService;
use Common\Service\GradeService;
use Mobile\Controller\WechatController;
use Mobile\Model\articleModel;
use Mobile\Model\moneylogModel;
use Mobile\Model\tmplModel;
use Mobile\Model\tmpmsgModel;
use Mobile\Model\withdrawModel;

class UserController extends LoginBaseController
{
    public $moneylogModel;
    public static $teamType_all='all';//所有类型
    public static $teamType_first=1;//直推
    public static $teamType_two=2;//间推
    public $withdrawModel;
    public $tmpl;
    public function __construct()
    {
        parent::__construct();
        $this->withdrawModel = new withdrawModel();
        $this->moneylogModel = new moneylogModel();
    }
    //查询出用户信息
    public function queryUserinfo(){
        $where['uid']=$this->uid;
        $data['orderData']['all']=OrderService::S()->queryCountOrderByWhere($where);
        $where['checked']=0;
        $data['orderData']['pending_payment']=OrderService::S()->queryCountOrderByWhere($where);
        $where['checked']=array(array('EQ',1),array('EQ',5),"OR");
        $data['orderData']['pending_delivery']=OrderService::S()->queryCountOrderByWhere($where);

        $data['userInfo']=UserService::S()->findUserInfo(array('uid'=>$this->uid),self::userFiled());
        $data['userInfo']['grade']=GradeService::S()->backGradeName($data['userInfo']['grade_id']);
        if($data['userInfo']){
            $this->ajax(200,'success',$data);
        }else{
            $this->ajax(202,'用户信息错误,请联系管理员');
        }
    }

    //用户基本信息字段
    public function userFiled(){
        $filed='uid,mobile,realname,nickname,refer_uid,refer_nickname,stock,headimgurl,grade_id';
        return $filed;
    }

    //查询用户余额信息
    public function balance(){
        $where['uid']=$this->uid;
        $user=UserService::S()->findUserInfo($where,'money,score,cash_money,stock');
        if(!$user){
            $this->ajax(202,'用户信息查询失败');
        }else{
            $this->ajax(200,'success',$user);
        }
    }

    //查询提货信息
    public function findTihuoInfo(){
        $where['is_tuihuo']=array('EGT',1);//0不予许退货,>0允许退货
        $filed='goods_id,goods_name,goods_pic,stock,shop_price,market_price';
        $data['goodsInfo']=GoodsService::S()->queryGoodsInfoByWhere($where,$filed);
        foreach ($data['goodsInfo'] as $k=>$v){
            $data['goodsInfo'][$k]['goods_pic']=C('UPYUN_DOMAIN').$v['goods_pic'];//$goodsInfo["grade{$this->member['grade_id']}_price"];
        }
        $data['userInfo']['stock']=UserService::S()->findFiled($this->uid,'stock');
        $this->ajax(200,'success',$data);
    }

    public function stockDetail(){
        $page_size = 20;//C("MOBILE_PAGESIZE");//分页条数
        $page = get('page',1);
        $where = array(
            'uid' => 2,//$this->uid,
            "mtype" =>4
        );
        $filed='log_id,uid,nickname,mtype,content,logtype,money,un_lock,create_time,manager_username,note';
        $datalist = MoneyLogService::S()->getLogList($where, $page,$page_size,$filed);
        $a_count = MoneyLogService::S()->getCount($where);//总的记录数量
        $ascCount = MoneyLogService::S()->sumCountMoney($where);//总金额
        $desCount = MoneyLogService::S()->sumCountMoney($where,'dec');//总金额
        $moneyCount=$ascCount-$desCount;
        $totalpage = ceil($a_count/$page_size);//向上取整,总的页码数
        $data['list']=$datalist;
        $data['totalpage']=$totalpage;
        $data['count_money']=$moneyCount;
        $this->ajax(200,'success',$data);
    }

    //查询等级立碑
    public function gradeList(){
        $filed='grade_id,grade_name,ord';
        $gradeList=GradeService::S()->gradeList(array(),$filed);
        $this->ajax(200,'success',$gradeList);
    }

    //我的团队
    public function myTeam(){
        $page=I('post.page');
        $pageNum=10;
        $type=I('post.type');
        if(empty($type)){
            $type=self::$teamType_all;
        }
        $grade_id=I('post.grade_id');
        if(empty($grade_id) ||$grade_id==0){
            $grade_id='all';
        }
        if($grade_id!='all'){
            $where['waoo_member.grade_id']=$grade_id;//array();
        }
        //查询出改用户下的所有下级
        //$backArray=array();
        $where['refer_uid']=2;//$this->uid;
        $fileds='uid,realname,nickname,mobile,create_time,refer_uid,waoo_member.grade_id,headimgurl,waoo_grade.grade_name';
        $filed='uid,realname,nickname,mobile,create_time,refer_uid,waoo_member.grade_id,headimgurl';
        $userInfo=UserService::S()->queryUserInfoOfGrade($where,$page,$pageNum,$fileds);
        $count=UserService::S()->countUser($where);
        if($type!=self::$teamType_first){ //不是直推
            //$this->ajax(200,'success',$userInfo);
            $twoUserInfo=array();
            foreach ($userInfo as $k => $v) {
                $where['refer_uid']=$v['uid'];
                $backArray = UserService::S()->queryUserInfo($where, $page, $pageNum, $filed);
                $twoUserInfo=array_merge($twoUserInfo,$backArray);
            }
            if($type==self::$teamType_two){ //间推
                $userInfo=$twoUserInfo;
            }else {//所有类型
                $userInfo=array_merge($userInfo,$twoUserInfo);
            }
        }
        $this->ajaxReturn(array('code'=>200,'msg'=>'success','data'=>$userInfo,'count'=>$count));
    }

    //查询我的积分
    public function moneydetail () {
        $bar_moth='month';
        $bar_day='today';
        $pageNum=I('page_num');//20;
        if(empty($pageNum) || $pageNum<=0){
            $pageNum=20;
        }
        $tab = I('post.tab');//('tab');//全部 推荐奖 区域奖 年终奖
        $bar = I('post.bar');///get('bar');//全部 本月 今日
        ///
        if($bar!=$bar_moth && $bar!=$bar_day){
            $bar='all';
        }
        $page = I('post.page');//get('page',1);
        if($page<=1){
            $page=1;
        }
        $where = array(
            'uid' => $this->uid,//$this->member['uid']
        );
        switch ($tab){
            case 'all':
                $where['mtype'] = array('in',array(1,5));
                break;
            case 'tuijian':
                $where['mtype'] = 1;
                $where['content'] = array('notlike','%区域%');
                break;
            case 'quyu':
                $where['mtype'] = 1;
                $where['content'] = array('like','%区域%');
                break;
            case 'year':
                $where['mtype'] = 5;
                break;
            default :
                $where['mtype'] = array('in',array(1,5));
                break;

        }

        if($bar==$bar_moth) {
            $where['create_time'] = array('between',array(date('Y-m-01 00:00:00'),date('Y-m-d H:i:s')));
        } elseif($bar==$bar_day) {
            $where['create_time'] = array('between',array(date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')));
        }
        $filed='log_id,nickname,content,money,order_nickname,create_time,logtype';
        //dump($where);die;
        $list =$this->moneylogModel
            ->field($filed)
            ->where($where)
            ->order('log_id desc')
            ->page($page,$pageNum)
            ->select();
        $orderModel = M('order');
        foreach($list as $k=>$v) {
            if($v['order_id']) {
                $list[$k]['nickname'] = $orderModel->where(array('order_id'=>$v['order_id']))->getField('nickname');
            }
        }
        if(!$list) {
            $this->ajax(200,'没有数据',$list,'list');
        }else{
            $back['pageCount']=ceil($this->moneylogModel->where($where)->count()/$pageNum);
            //$this->ajax(200,'success',);
            $back['code']=200;
            $back['msg']='success';
            $back['list']=$list;
            $select=I('post.where');
            if($select=='all'){//查询所有
                $data = array(
                    'month' => getAllMoneyByDate($this->uid,date('Y-m-01 00:00:00'),date('Y-m-d H:i:s')),
                    'day' => getAllMoneyByDate($this->uid,date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')),
                    'all' => getAllMoneyByDate($this->uid,date('2018-01-01 00:00:00'),date('Y-m-d 23:59:59'))
                );
                $back['count']=$data;
            }
            $this->ajaxReturn($back);
        }

    }

    //区域奖励
    public function area(){

        $page = post('page',1);
        $page_size=post('page_num',20);
        $where = array(
            'uid' => $this->uid,
            "mtype" =>array('in',array(1,12)),
            'content' => array('like','%区域%')
        );
        $filed='log_id,nickname,content,money,order_nickname,create_time';
        $datalist = MoneyLogService::S()->getLogList($where,$page,$page_size,$filed);//$this->moneylogModel->getMoneylogList($where, $page,$page_size);

        $totalpage = ceil($this->moneylogModel->where($where)->count()/$page_size);//向上取整,总的页码数
        //$this->assign('totalpage',$totalpage);
        $data['code']=200;
        $data['msg']='success';
        $data['page_count']=$totalpage;
        $data['data']=$datalist;
        $this->ajaxReturn($data);
    }

    /* 申请代理 */
    public function apply() {
        $applyModel = M('apply');
        //$uid = $this->uid;
        $data = $_POST;
        if(!$data['grade_id']) {
            $this->ajax(202,'请选择等级');
        }
        if($this->member['grade_id']>=$data['grade_id']) {
            $this->ajax(202,'无法申请低等级代理');
        }
        if($data['grade_id']<5 || $data['grade_id']>6) {
            $this->ajax(202,'代理申请等级不合法');
        }
        if(!$data['province']||!$data['city']||!$data['county']) {
            $this->ajax(202,'请选择地区');
        }
        //自己有等待中申请
        $where = array(
            'uid' => $this->uid,
            'status' => 0
        );
        $old = $applyModel->where($where)->find();
        if($old) {
            $this->ajax(202,'您的申请还在审核中，请耐心等待');
        }
        $apply = array(
            'uid' => $this->uid,
            'area_id' => $data['province_id'],
            'money' => 29800,
            'type' => 2,
            'create_time' => date('Y-m-d H:i:s'),
            'grade_id' => $data['grade_id'],
            'delivery' => json_encode(array(
                'province' => $data['province'],
                'city' => $data['city'],
                'county' => $data['county']
            ))
        );
        $applyModel->add($apply);
        $this->ajax(200,'已提交申请，请等待审核');
    }

    /**
     * 申请代理列表
     */
    public function applyList(){
        $min =$this->member['grade_id']==5?($this->member['grade_id']+1):5;
        $where = array(
            'grade_id' => array('between',array($min,6))
        );
        //dump($where);die;
        $filed='grade_id,grade_name,ord';
        $gradeArr = M('grade')->field($filed)->where($where)->select();
        if(empty($gradeArr)){
           $this->ajax(202,'empty');
        }else{
            $this->ajax(200,'success',$gradeArr);
        }
    }

    /**
     *文章列表
     */
    public function articleLists() {
        $articleModel=new articleModel();
        $page = post("page",1);
        $pagesize=post('page_num',20);
        $atype_id = post('atype_id');
        $qtype=post('qtype','first');
        $title = post("title");
        //文章
        $where = array(
            "status" => 1,
            'uid' => 0,//管理员发布
            "post_time" => array("elt",date("Y-m-d H:i:s")),
            "is_check" => 1,
        );
        if(trim($title) != ""){
            $where["title"] = array("like","%{$title}%");
        }
        if($atype_id){
            $where["atype_id"] = $atype_id;
        }
        //dump($where);die;
        $filed='atype_id,article_id,title,description,create_time,thumb';
        $article_list = ArticleService::S()->queryList($where,$page,$pagesize,$filed);
        $bankGround=array();
        foreach ($article_list as $k=>$v){
            if($k==0){
                $bankGround[]=array(
                    'img'=>C('UPYUN_DOMAIN').$article_list[$k]['thumb'],
                    'url'=>get_domain()."/mobile/article?article_id={$v['article_id']}"
                );
            }
            $article_list[$k]['thumb']=C('UPYUN_DOMAIN').$article_list[$k]['thumb'];
        }
        //$articleModel->getArticleList($where, $page);
        //dump($article_list);die;
        $data['code']=200;
        $data['msg']='success';
        $data['backGround']=$bankGround;
        $data['data']=$article_list;
        if($qtype=='two'){
            $this->ajaxReturn($data);
        }
        $count = $articleModel->getArticleCount($where);
        $totalpage = ceil($count/$pagesize);
        $type_list=ArticleService::S()->queryTypeList(array(),'atype_id,atype_name,atype_ord');
        //dump($typelist);die;
        $data['data_type']=$type_list;
        $data['page_count']=$totalpage;
        $this->ajaxReturn($data);
    }
    /*
     * 文章详情
     */
    public function articleDetail(){

        $article_id = post('article_id');
        //$refresh = get('refresh');
        //$filed='content';
        $filed='article_id,title,content,create_time,thumb,content';
        $article =ArticleService::S()->findDetail(array('article_id'=>$article_id),$filed) ;//$this->_getArticle($article_id);
        if(empty($article)){
            $this->ajax(202,"当前文章已被删除","/mobile/");
        }
        $article['content'] = stripslashes($article['content']);
        $article['content']=htmlspecialchars_decode($article['content']);
        $article['content']=str_replace('src="','src="'.get_domain(),$article['content']);
        $article['thumb']=C('UPYUN_DOMAIN').$article['thumb'];
        $article['shop']=C('SHARE_DEFAULT_TITLE');
        //判断是否是付费的
        /*
         * 设置分享的图片
         */
        $this->ajax(200,'success',$article);
        //dump($article);die;
    }

    //检查验证码
    public function checkCode($mobile=null){
        $code=I('post.code');
        if(empty($mobile)){
            $mobile=I('post.mobile');
        }
        //dump($_SESSION);die;
        if($_SESSION[$mobile-"code"]!=$code){
            $this->ajax(202,'验证码错误');
        }
    }
    //兑换列表
    public function exchangeIndex(){
        //查询出可体现银行
        $backModel=M('bankcom');
        $filed='eid,status,ecom_name';
        $data['back']=$backModel->field($filed)->where(array('status'=>1))->select();
        $data['max_shouxufei']=C('MAX_SHOUXU');//手续费率
        $data['beishu']=C('WITHDRAW_DOUBLE');
        $this->ajax(200,'success',$data);
        //$data['moneyList']='';
    }
    public function tixian(){
        $must = array(
            "realname","bankname","mobile","atm_money"
        );
        $allow =array(
            "realname","bankname","mobile","alipay","atm_money","kaihuhang","bankcard","code"
        );
        //$this->checkCode();
        if($_POST['bankname'] != "微信钱包"){
            if(empty($_POST['kaihuhang']) OR empty($_POST['bankcard'])){
                $this->ajax(202,"请检查是否填写完整");
            }
        }else{
            $_POST['kaihuhang'] = "";
            $_POST['bankcard'] = "";
        }
        $data = param_filter($_POST, $allow,$must,true,true);
        if(empty($data)){
            $this->ajax(202,"请检查是否填写完整");
        }
        //判断是否有足够的钱
        $memberinfo = UserService::S()->findUserInfo(array('uid'=>$this->uid));//$this->getMemberInfobyUid($this->uid);
        if($memberinfo['money'] < $data['atm_money']){
            $this->ajax(202,"余额不足,兑换不了哦~");
        }
        //判断是不是100的整数倍
        $withdraw_double = C('WITHDRAW_DOUBLE');
        $withdraw_rate = C('WITHDRAW_RATE');

        if($withdraw_double>0){
            if($data['atm_money']%$withdraw_double>0 || ($data['atm_money']<=0)){
                $this->ajax(202,"兑换金额只能是".$withdraw_double."的整数倍哦");
            }
        }
        $data['shouxufei'] = $data['atm_money'] * $withdraw_rate;//兑换手续费
        $max_shouxufei = C('MAX_SHOUXU');//手续费封顶
        if($max_shouxufei>0){
            if($data['shouxufei']>$max_shouxufei){
                $data['shouxufei'] = $max_shouxufei;//手续费封顶
            }
        }
        $tixian_money = round($data['atm_money']-$data['shouxufei'],2);
        //扣除佣金
        $data_money = array(
            "money" => array("exp","money-".$data['atm_money']),
            "tixian" => array("exp","tixian+".$data['atm_money']),
            "geshui_money" => array("exp","geshui_money+".$data['shouxufei']),
        );
        $res = UserService::S()->updateMemberInfoByUid($this->uid, $data_money);

        $data['openid'] = $this->member['openid'];

        if($res){
            //写兑换记录,流水
            $data['uid'] = $this->uid;
            $data['create_time'] = date("Y-m-d H:i:s");
            $data['update_time'] = date("Y-m-d H:i:s");
            $data["status"] = 0;
            $data['withdraw_money'] = $tixian_money;


            $withdraw = $this->withdrawModel->addWithdraw($data);
            if($withdraw){
                //发送模板消息
                $this->_tixianMsg($data);//给用户发兑换通知
                //$uids = C('NEW_WITHDRAW_UIDS');
                $this->ajax(200,"已提交申请,请等待财务审核");
            }
        }
        $this->ajax(200,"申请失败");
    }

    /*
    * 兑换提醒
    */
    protected function _tixianMsg($tixian){
        //判断是否关注, 没关注就别发了

        $userinfo = $this->member;

        if(!$userinfo['openid']){
            //TODO
            return false;
        }
        //发送模板消息
        $msg = $this->_tixianTmp($tixian,$userinfo);//拼接模板消息

        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列

        return true;
    }
    /*
    * 升级消息
    *
    {{first.DATA}}

    兑换金额:{{money.DATA}}
    兑换时间:{{timet.DATA}}
    {{remark.DATA}}

    * 拼接模板消息
    */
    protected function _tixianTmp($tixian,$userinfo){

        //读取模板id并缓存
        $tmpl = S("TMPL");
        if(empty($tmpl) || 1){
            $tmpl = $this->_getTmpId();//获取模板id
            S("TMPL",$tmpl);
        }

        $this->tmpl = $tmpl;
        $tmp_id = $this->tmpl['TIXIAN_TIJIAO']['tmp_id'];
        $color = $this->tmpl['TIXIAN_TIJIAO']['color'];

        $url = get_domain()."/mobile/withdraw/lists/";
        $footer ='\\n'."点击查看详情...";
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode("你提交了兑换申请,请等待管理员审核~"),
                    'color' => $color
                ),
                'money' => array(
                    'value' => urlencode($tixian['atm_money']."元"),//原先等级
                    'color' => $color,
                ),
                'timet' => array(
                    'value' => urlencode($tixian['create_time']),//new等级
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );

        return $msg = urldecode(json_encode($msg));
    }
    //获取数据库中的模板消息id
    protected function _getTmpId(){
        $tmplModel = new tmplModel();
        $where = array(

        );
        $res = $tmplModel->getTmplList($where);
        $new = array();
        if(!empty($res)){
            foreach($res as $k=>$v){
                $new[$v['tmp_name']] = $v;
            }
        }
        return $new;
    }

    //绑定手机号码
    public function bind_mobile(){
        $phone=I('post.mobile');
        $code=I('post.code');
        //dump($_SESSION);die;
        if(!is_phone($phone)){
            $this->ajax(202,'手机号码错误');
        }
        //判断手机号码是否已绑定
        $re=UserService::S()->findUserInfo(array('mobile'=>$phone));
        if($re){
            $this->ajax(202,'手机号码已被绑定');
        }
        if($_SESSION[$phone."-code"]!=$code){
            $this->ajax(202,'验证码错误');
        }
        $re=UserService::S()->updateMemberInfoByUid($this->uid,array('mobile'=>$phone));
        if($re===false){
            $this->ajax(202,'绑定失败');
        }else{
            $this->ajax(200,'绑定成功');
        }
        //$userInfo=UserService::S()->findUserInfo(array('uid'=>));
    }

    //我要开店
    public function open_store(){
        $where['ischeck']=1;
        $filed='market_price,shop_price,goods_name,goods_pic,goods_id,grade_id';
        $where['goods_id']=array(
            'in',array(2,3)
        );
        $goods=GoodsService::S()->queryGoodsInfoByWhere($where,$filed);
        foreach ($goods as $k=>$v){
            $goods[$k]['goods_pic']=C('UPYUN_DOMAIN').$v['goods_pic'];
        }
        //dump($goods);die;
        $this->ajax(200,'success',$goods);
    }

    //我的推广二维码
    public function myqrcode(){
        $wechat=new WechatController();
        if($this->member['grade_id']<=1) {
            //$this->error2('请先成为代理');
            $this->ajax(202,'请先成为代理');
        }
        $userinfo = $this->member;
        //获取用户信息
        $wxuser=$wechat->getUserInfo($userinfo['openid']);
        if(!empty($wxuser)){
            $userinfo['nickname'] = $wxuser['nickname'] ? $wxuser['nickname'] : $userinfo['nickname'];
            $userinfo['headimgurl'] = $wxuser['headimgurl'] ? $wxuser['headimgurl'] : $userinfo['headimgurl'];
        }
        $share_pic = ThirdService::S()->makeshare($userinfo,1);//生成分享二维码
        $this->ajax(200,'success',$share_pic,'share_img');
    }

    //提现记录
    public function withdraw_list(){
        //0提交待审核,1财务已打款,2审核拒绝
        $page_size = 20;//C("MOBILE_PAGESIZE");//分页条数
        $page = get("page",1);
        $where = array(
            "uid" =>397//$this->uid
        );
        $filed='realname,bankname,bankcard,withdraw_money,atm_money,shouxufei,status,create_time';
        $datalist =WithdrawService::S()->queryList($where,$page,$page_size,$filed) ;//$this->withdrawModel->getWithdrawList($where,$page,$page_size);

        $a_count = WithdrawService::S()->queryCount($where);//$this->withdrawModel->where($where)->count();//总的记录数量
        $totalpage = ceil($a_count/$page_size);//向上取整,总的页码数
        //$this->assign('totalpage',$totalpage);
        $data['list']=$datalist;
        $data['totalpage']=$totalpage;
        $data['count_money']=WithdrawService::S()->querySumMoney($where);
        $this->ajax(200,'success',$data);
    }

}